import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yqys_target/extensions/hex_color.dart';
import 'package:yqys_target/gen/assets.gen.dart';
import 'package:yqys_target/utils/xh_share.dart';
import 'package:yqys_target/utils/yq_colors.dart';
import 'package:yqys_target/pages/image_preview_page.dart';
import 'package:yqys_target/widgets/donation_dialog.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'dart:math' as math;

import '../widgets/yq_progress.dart';

const _kButtonHeight = 48.0;

class RaiseDetailPage extends StatefulWidget {
  final double progress;
  final String progressText;
  final String target;
  final String title;
  final String description;

  const RaiseDetailPage({
    super.key,
    required this.progress,
    required this.progressText,
    required this.target,
    required this.title,
    required this.description,
  });

  @override
  State<RaiseDetailPage> createState() => _RaiseDetailPageState();
}

class _RaiseDetailPageState extends State<RaiseDetailPage> {
  final ScrollController _scrollController = ScrollController();
  double _scrollOpacity = 0.0;
  bool _isDark = true;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    final offset = _scrollController.offset;
    final opacity = (math.min(1, math.max(0, offset / 50))).toDouble();
    final isDark = offset < 50;

    if (opacity != _scrollOpacity || isDark != _isDark) {
      setState(() {
        _scrollOpacity = opacity;
        _isDark = isDark;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final backgroundColor = Color.lerp(
      Colors.transparent,
      Colors.white,
      _scrollOpacity,
    );

    final textColor = Color.lerp(
      Colors.white,
      Colors.black,
      _scrollOpacity,
    );

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: _isDark ? Brightness.light : Brightness.dark,
        statusBarBrightness: _isDark ? Brightness.light : Brightness.dark,
      ),
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        body: Stack(
          children: [
            const _HeaderBgImage(),
            MainScroll(
              scrollController: _scrollController,
              textColor: textColor,
              backgroundColor: backgroundColor,
              progress: widget.progress,
              progressText: widget.progressText,
              target: widget.target,
              title: widget.title,
              description: widget.description,
            ),
            // 固定在底部的捐赠按钮
            const DonateButton(),
          ],
        ),
      ),
    );
  }
}

class DonateButton extends StatelessWidget {
  const DonateButton({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return const Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: _DonatButton(),
    );
  }
}

class MainScroll extends StatelessWidget {
  const MainScroll({
    super.key,
    required ScrollController scrollController,
    required this.textColor,
    required this.backgroundColor,
    required this.progress,
    required this.progressText,
    required this.target,
    required this.title,
    required this.description,
  }) : _scrollController = scrollController;

  final ScrollController _scrollController;
  final Color? textColor;
  final Color? backgroundColor;
  final double progress;
  final String progressText;
  final String target;
  final String title;
  final String description;

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        // 透明AppBar和头部背景图
        _DetailAppBar(textColor: textColor, backgroundColor: backgroundColor),
        const _ScrollHeadPlaceHolder(),
        // 项目基本信息
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverToBoxAdapter(
            child: _DetailSectionOne(
              progress: progress,
              progressText: progressText,
              target: target,
              title: title,
              description: description,
            ),
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            height: 20,
          ),
        ),
        const SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverToBoxAdapter(
            child: _DetailSectionTwo(),
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            height: 16,
          ),
        ),
        const SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverToBoxAdapter(
            child: _DetailSectionThree(),
          ),
        ),
        // 底部空白
        SliverToBoxAdapter(
          child: Container(
            height: XHShare.bottomSafeHeight + 16 + _kButtonHeight,
          ),
        ),
      ],
    );
  }
}

class _DetailSectionThree extends StatelessWidget {
  const _DetailSectionThree();

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: Container(
        padding: const EdgeInsets.only(top: 16, left: 16, right: 16, bottom: 5),
        color: Colors.white,
        child: const Column(
          children: [
            _InfoItem(
              title: '联系邮箱：',
              content: _TextContent(
                text: '1585242542@qq.com',
              ),
            ),
            SizedBox(
              height: 8,
            ),
            _InfoItem(
              title: '机构官网：',
              content: _TextContent(
                text: 'www.123321.com',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _DetailSectionTwo extends StatelessWidget {
  const _DetailSectionTwo();

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
          color: Colors.white,
          child: const Column(
            children: [
              SizedBox(height: 8),
              _InfoItem(
                title: '服务对象:',
                content: _TextContent(
                  text:
                      '1.恩施义工协会收集广大益友捐赠的物资\n 2.由恩施义工协会会长亲自担保，送往山 区交予苦难儿童\n 3.活动结束会进行物资公证。',
                ),
              ),
              SizedBox(height: 8),
              _InfoItem(
                title: '益事流程：',
                content: _TextContent(
                  text:
                      '1.恩施义工协会收集广大益友捐赠的物资\n 2.由恩施义工协会会长亲自担保，送往山 区交予苦难儿童\n 3.活动结束会进行物资公证。',
                ),
              ),
              SizedBox(height: 8),
              _InfoItem(
                title: '益事时间：',
                content: _TextContent(
                  text:
                      '''需求：我们需要一年级教材100套，二年级教材300套，三年级教材150套，四年级教材50套，五年级教材200套，六年级教材80套左右，另需要100张课桌\n用途：教学日常都需要，改善学生就教学环境''',
                ),
              ),
            ],
          ),
        ));
  }
}

class _DetailAppBar extends StatelessWidget {
  const _DetailAppBar({
    required this.textColor,
    required this.backgroundColor,
  });

  final Color? textColor;
  final Color? backgroundColor;

  @override
  Widget build(BuildContext context) {
    return SliverAppBar(
      pinned: true,
      elevation: 0,
      title: Text(
        "益事详情",
        style: TextStyle(color: textColor),
      ),
      backgroundColor: backgroundColor,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios, color: textColor),
        onPressed: () => Navigator.of(context).pop(),
      ),
    );
  }
}

class _ScrollHeadPlaceHolder extends StatelessWidget {
  const _ScrollHeadPlaceHolder();

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        height: 50,
      ),
    );
  }
}

class _HeaderBgImage extends StatelessWidget {
  const _HeaderBgImage();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Image.asset(
        Assets.images.raiseDetailHeader.path,
        fit: BoxFit.contain,
      ),
    );
  }
}

class _DonatButton extends StatelessWidget {
  const _DonatButton();

  void _showDonationDialog(BuildContext context) {
    SmartDialog.show(
      builder: (_) => DonationDialog(
        userBalance: 35.0, // 示例用户余额
        remainingAmount: 100.0, // 示例剩余可捐赠金额
        greenEnergy: 232.0, // 示例绿色能量
        onConfirmDonation: (amount) {
          // TODO: 处理确认捐赠
          SmartDialog.dismiss();
        },
        onClose: () => SmartDialog.dismiss(),
        onExchange: () {
          // TODO: 处理前往兑换
          SmartDialog.dismiss();
          // 跳转到兑换页面
        },
      ),
      alignment: Alignment.bottomCenter,
      clickMaskDismiss: true,
      maskColor: Colors.black.withOpacity(0.5),
      useAnimation: true,
      animationTime: const Duration(milliseconds: 200),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
          bottom: XHShare.bottomSafeHeight, top: 16, left: 16, right: 16),
      child: ElevatedButton(
        onPressed: () => _showDonationDialog(context),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.green,
          fixedSize: const Size(double.infinity, _kButtonHeight),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
        ),
        child: const Text(
          '捐赠',
          style: TextStyle(
            fontSize: 20,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

class _DetailSectionOne extends StatelessWidget {
  final double progress;
  final String progressText;
  final String target;
  final String title;
  final String description;

  const _DetailSectionOne({
    required this.progress,
    required this.progressText,
    required this.target,
    required this.title,
    required this.description,
  });

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: Container(
        padding: const EdgeInsets.all(16),
        color: Colors.white,
        child: Column(
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _ProgressComponent(progress: progress, progressText: progressText, target: target),
            const SizedBox(height: 8),
            Text(
              description,
              style: TextStyle(
                color: YQColors.secondary,
                fontSize: 14,
              ),
            ),
            const _SectionImageSwiper(),
            const SizedBox(height: 8),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _InfoItem(
                  title: '发起机构:',
                  content: _OrganizationContent(
                    name: '恩施州义工总会',
                    imageUrl: Assets.icons.homeCateItemComingsoon.path,
                  ),
                ),
                const _InfoItem(
                  title: '益事时间:',
                  content: _TimeContent(
                    startTime: '2028-11-24 14:00',
                    endTime: '2018-12-12 14:00',
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class _ProgressComponent extends StatelessWidget {
  const _ProgressComponent({
    required this.progress,
    required this.progressText,
    required this.target,
  });

  final double progress;
  final String progressText;
  final String target;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ProgressWidget(
          progress: progress,
          progressText: progressText,
          target: target,
          gradientColors: [
            HexColor.fromHexWithoutAlpha("#F5AA3B"),
            HexColor.fromHexWithoutAlpha("#E57017"),
          ],
        ),
        const SizedBox(height: 8),
        ProgressInfo(progressText: progressText, target: target),
      ],
    );
  }
}

class _SectionImageSwiper extends StatelessWidget {
  const _SectionImageSwiper();

  @override
  Widget build(BuildContext context) {
    final List<String> images = List.generate(
      5,
      (index) => Assets.images.project1.path,
    );

    return Container(
      padding: const EdgeInsets.all(16),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: List.generate(
            images.length,
            (index) => GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ImagePreviewPage(
                      imageUrls: images,
                      initialIndex: index,
                      heroTagPrefix: 'raise_detail_image',
                    ),
                  ),
                );
              },
              child: Hero(
                tag: 'raise_detail_image_$index',
                child: Container(
                  width: 60,
                  height: 60,
                  margin: const EdgeInsets.only(right: 8),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    image: DecorationImage(
                      image: AssetImage(images[index]),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _InfoItem extends StatelessWidget {
  final String title;
  final Widget content;

  const _InfoItem({
    required this.title,
    required this.content,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const SizedBox(width: 20),
          Expanded(
            child: Align(
              alignment: Alignment.centerRight,
              child: content,
            ),
          ),
        ],
      ),
    );
  }
}

// 机构信息布局
class _OrganizationContent extends StatelessWidget {
  final String name;
  final String imageUrl;

  const _OrganizationContent({
    required this.name,
    required this.imageUrl,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            image: DecorationImage(
              image: AssetImage(imageUrl),
              fit: BoxFit.cover,
            ),
          ),
        ),
        const SizedBox(width: 8),
        Flexible(
          child: Text(
            name,
            style: TextStyle(
              fontSize: 14,
              color: YQColors.secondary,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }
}

// 时间信息布局
class _TimeContent extends StatelessWidget {
  final String startTime;
  final String endTime;

  const _TimeContent({
    required this.startTime,
    required this.endTime,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          'TO',
          style: TextStyle(
            fontSize: 14,
            color: YQColors.primary,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(width: 8),
        Flexible(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                startTime,
                style: TextStyle(
                  fontSize: 14,
                  color: YQColors.secondary,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 4),
              Text(
                endTime,
                style: TextStyle(
                  fontSize: 14,
                  color: YQColors.secondary,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ],
    );
  }
}

// 普通文本布局
class _TextContent extends StatelessWidget {
  final String text;

  const _TextContent({
    required this.text,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 14,
        color: YQColors.secondary,
        height: 1.5,
      ),
      textAlign: TextAlign.right,
      maxLines: null,
    );
  }
}
